// charging.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

const app = getApp()
var util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperbox: app.globalData.swiperbox,
    swiper: app.globalData.swiper,
    gradientColor:{
      '0%': '#F03732',
      '100%': '#FFA71E'
    },
    rate:0,
    pwdMsg:{
      time:0,
      totalTime:7200,
      pwd:'123456',
    },
    timeData: {},
    sn:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var pwdMsg = JSON.parse(options.pwdMsg);
    var timeData = wx.getStorageSync('timeData');
    var rate = wx.getStorageSync('rate');
    if (options.version==3) {
      var bluetoothIDs = JSON.parse(options.bluetoothIDs)
      wx.setStorageSync('bluetoothIDs', bluetoothIDs);
      that.setData({
        deviceId: bluetoothIDs.deviceId,
        servicesUUID: bluetoothIDs.servicesUUID,
        readId: bluetoothIDs.readId,
        writeId: bluetoothIDs.writeId
      })
    }
    var swiper = wx.getStorageSync('swiper')
    that.setData({
      sn: options.sn,
      pwdMsg: pwdMsg,
      version: options.version,
      orderid: options.orderid,
      rate: rate,
      timeData: timeData,
      swiper: app.globalData.swiper.length == 0 ? swiper : app.globalData.swiper,
      shopname: options.shopname
    })
    
    that.audio();
  },
  audio: function () {
    var audioCtx = wx.createInnerAudioContext()
    if (this.data.pwdMsg !== '') {
      const version = wx.getSystemInfoSync().SDKVersion;
      if (util.compareVersion(version, '2.3.0') >= 0) {
        wx.setInnerAudioOption({
          mixWithOther: true,
          obeyMuteSwitch: false
        })
      }
      audioCtx.src = "http://file.gcb360.com/mima.mp3";
      audioCtx.play()
      audioCtx.onError(function (res) {
        console.log(`音频错误：`,res)
      })
    }
  },
  // 计时器比例
  timeChange(e) {
    var that = this;
    var day = e.detail.days;
    var hour = e.detail.hours;
    var min = e.detail.minutes;
    var sec = e.detail.seconds;
    var time = day*24*60*60 + hour*60*60 + min*60 + sec;
    var totalTime = that.data.pwdMsg.totalTime;
    var rate = ((totalTime - time) / totalTime)*100;
    that.setData({
      timeData: e.detail,
      rate:rate
    });
    wx.setStorageSync("rate", rate)
    wx.setStorageSync("timeData",e.detail)
  },
  timeFinished:function(){
    this.endTap()
  },
  // 更换密码
  pwdChange:function(){
    var that = this;
    var sn = that.data.sn;
    var data = { sn: sn, id: that.data.orderid };
    app.post('order/resetPasswd',data).then((res)=>{
      console.log(res)
      if(res.code == 200){
        var pwd = ['pwdMsg.pwd']
        that.setData({
          [pwd]: res.entity.passwd
        })
        if (that.data.version==3) {
          wx.navigateTo({
            url: '../bluetooth/bluetooth?sn=' + sn + '&pwd=' + res.entity.passwd + '&resource="charging"',
          })
          // that.writeData(res.entity.passwd)
        }
      }else{
        Toast.loading(res.message);
      }
    }).catch((errMsg)=>{
      console.log(errMsg);
    })
  },
  // 故障上报
  errorTap:function(){
    wx.navigateTo({
      url: '../errorReport/errorReport?sn='+this.data.sn +'&version='+this.data.version,
    })
  },
  // 结束充电
  endTap:function(){
    var that = this;
    var orderId = that.data.orderid;
    var data = { id: orderId };
    app.post('order/closeOrder', data).then((res) => {
      if (res.code == 200) {
        const countDown = this.selectComponent('.control-count-down');
        this.setData({
          rate: 100,
          timeData: {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0,
            milliseconds: 0
          }
        })
        countDown.pause();
        app.globalData.order = null
        wx.switchTab({
          url: '../map/map'
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    })
  },
  // 帮助中心
  helpTap:function(){
    wx.switchTab({
      url: '../help/help'
    })
  },
  // 向低功耗蓝牙设备特征值中写入二进制数据 6.0
  writeData(pwd) {
    var that = this;
    let buffer = util.hexStringToArrayBuffer(pwd);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.servicesUUID,
      characteristicId: that.data.writeId,
      value: buffer,
      success: function (res) {
        // 设备返回的方法
        console.log('7.0writeBLECharacteristicValue success:', res.errMsg)
        that.readData()

      }, fail: function (res) {
        console.log('7.0writeBLECharacteristicValue--fail:', res, res.errMsg)
      }
    })
  },
  // 读取低功耗蓝牙设备的特征值的二进制数据值 7.0
  readData(uuid) {
    var that = this;
    wx.readBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.servicesUUID,
      characteristicId: that.data.readId,
      success: function (res) {
        // 设备返回的方法
        console.log('readBLECharacteristicValue:', res.errCode)
        wx.onBLECharacteristicValueChange(function (res) {
          var nonceId = util.ab2hex(res.value)
          console.info("蓝牙测试返回的数据", res.value, nonceId);
          var nonceId = util.ab2hex(res.value)
        })
      }, fail: function (res) {
        console.log('readBLECharacteristicValue--fail:', res.errCode)
      }
    })
  },
  phone:function(){
    wx.makePhoneCall({
      phoneNumber: '400-060-2006'
    })
  },
})